package com.tuniu.agents.impl.flight;

import com.tuniu.agents.advisor.ChatEnvironmentMemory;
import com.tuniu.agents.agent.AgentManagerGroup;
import com.tuniu.agents.common.agent.Recommender;
import com.tuniu.agents.common.handler.IStreamResponseHandler;
import com.tuniu.agents.tools.flights.domestic.oneway.FlightLowPriceQueryTool;
import com.tuniu.agents.tools.flights.domestic.roundtrip.RoundFlightLowPriceQueryTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;


public class FlightRecommender extends Recommender {

    private static final Logger logger = LoggerFactory.getLogger(FlightRecommender.class);

    @Autowired(required = false)
    private ChatEnvironmentMemory chatEnvironmentMemory;

    public FlightRecommender(AgentManagerGroup agentManagerGroup, String agentId, String promptTemplateId, IStreamResponseHandler streamResponseHandler) {
        super(agentManagerGroup, agentId, promptTemplateId, streamResponseHandler, false, false);
    }

    public FlightRecommender(AgentManagerGroup agentManagerGroup, String agentId, String promptTemplateId) {
        super(agentManagerGroup, agentId, promptTemplateId);
    }

    @Override
    public Flux<String> stream(String conversationId, List<Message> messages, Map<String, Object> context) {
        String message = messages.get(0).getText();
        if(message == null){
            logger.error("flight agent error,message=null");
            return Flux.just("flight agent error,message=null");
        }

        // json to markdown
        String flightsMarkdown;
        if (StringUtils.isBlank((String) chatEnvironmentMemory.get(conversationId, "backDepartureDate"))) {
            flightsMarkdown = FlightLowPriceQueryTool.buildMarkdown(message);
        } else {
            flightsMarkdown = RoundFlightLowPriceQueryTool.buildMarkdown(message);
        }

        Flux<String> flux = this.chatClientRequestSpec(conversationId, List.of(new UserMessage(flightsMarkdown)), context).stream().content();
        Map<String, Object> params = Map.of("message", message,"conversationId",conversationId);
        return streamResponseHandler == null ? flux : streamResponseHandler.handle(params,flux);
    }
}